package com.zhentao.utils;

import com.zhentao.nlz.project.login.TMenu;

import java.util.ArrayList;
import java.util.List;

public class MenuHelper {

    /**
     * 使用递归方法建菜单
     *
     * @param sysMenuList
     * @return
     */
    public static List<TMenu> buildTree(List<TMenu> sysMenuList) {
        List<TMenu> trees = new ArrayList<>();
        for (TMenu sysMenu : sysMenuList) {
            Integer parentId = sysMenu.getParentId();
            if (parentId != null && parentId.longValue() == 0) {
                trees.add(findChildren(sysMenu, sysMenuList));
            }
        }
        return trees;
    }


    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public static TMenu findChildren(TMenu menu, List<TMenu> treeNodes) {
        menu.setChildren(new ArrayList<TMenu>());
        for (TMenu it : treeNodes) {
            Integer parentId = it.getParentId();
            if (parentId != null && menu.getMenuId().longValue() == parentId.longValue()) {
                // 如果 sysMenu 的 children 为空，则初始化为新的 ArrayList
                if (menu.getChildren() == null) {
                    menu.setChildren(new ArrayList<>());
                }
                menu.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return menu;
    }

}